package cloudoer.su.action;

import cloudoer.su.base.impl.BaseAction;
import cloudoer.su.entity.Menu;
import cloudoer.su.entity.Role;
import cloudoer.su.entity.User;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.*;

@Controller
@Scope("prototype")
public class IndexAction extends BaseAction {
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String indexUI(){
        return "success";
    }

    public String westUI(){
        return "success";
    }

    public String loginUI(){
        return "success";
    }

    public String login(){
        User temp = userService.login(user);
        if (temp == null){
            return "error";
        }else {
            ActionContext actionContext = ActionContext.getContext();
            List<Menu> menuList = (List<Menu>) actionContext.getApplication().get("systemMenus");
            List<Menu> menuTree = (List<Menu>) actionContext.getApplication().get("systemMenuTree");
            if ((menuList == null || menuList.size() < 1) && (menuTree == null || menuTree.size() < 1)){
                menuList = menuService.getAll();
                menuTree = menuService.getAllByGrade();
                actionContext.getApplication().put("systemMenus", menuList);
                actionContext.getApplication().put("systemMenuTree", menuTree);
            }
            actionContext.getSession().put("user", temp);
            Set<Menu> userMenuSet = new HashSet<Menu>();
            for (Role r : temp.getRoles()){
                userMenuSet.addAll(r.getMenus());
            }
            List<Menu> userMenus = new ArrayList<Menu>(userMenuSet);
            actionContext.getSession().put("userMenus", userMenus);
            Collection<Menu> userMenuTree = menuListToTree(userMenus, menuTree);
            actionContext.getSession().put("userMenuTree",userMenuTree);
            System.out.println(userMenuTree);
            return "success";
        }
    }

    private Collection<Menu> menuListToTree(List<Menu> list, Collection<Menu> tree){
        Collection<Menu> c = new HashSet<Menu>(tree);
        boolean tag = false;
        for (Menu m : tree){
            tag = false;
            for (Menu menu : list){
                if (m.equals(menu)){
                    menuListToTree(list, m.getLower());
                    tag = true;
                }
            }
            if (! tag){
                c.remove(m);
            }
        }
        return c;
    }
}
